package com.example.firstapp.storeData.SQLite

import android.annotation.SuppressLint
import android.content.ContentValues
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.firstapp.R
import com.example.firstapp.databinding.ActivitySqliteBinding

class SQLiteActivity : AppCompatActivity() {
    @SuppressLint("Range")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sqlite)
        val binding  = ActivitySqliteBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val dbHelper = SQLite1(this,"bookStore.db",1)
        binding.createDatabase.setOnClickListener {
            dbHelper.writableDatabase
//            Toast.makeText(this, "创建成功",
//                Toast.LENGTH_SHORT).show()
        }

        val dbHelper2 = `SQLite2-upgrade`(this,"bookStore.db",3)
        binding.updateDatabase.setOnClickListener {
            dbHelper2.writableDatabase
            Toast.makeText(this, "更新成功",
                Toast.LENGTH_SHORT).show()
        }
        val dbHelper3 = `SQLite2-upgrade`(this,"bookStore.db",3)
        binding.insert.setOnClickListener {
            val db = dbHelper3.writableDatabase
            val value = ContentValues().apply{
                val name =  binding.name.text.toString()
                val author =  binding.author.text.toString()
                val pages =  binding.pages.text.toString().toInt()
                val price =  binding.price.text.toString().toFloat()
                put("name", name)
                put("author", author)
                put("pages", pages)
                put("price", price)
                println("添加成功")
            }
            db.insert("Book",null, value)
        }
        binding.select.setOnClickListener {
            val db = dbHelper3.writableDatabase
            // 查询Book表中所有的数据
            val cursor = db.query("Book", null, null, null, null, null, null)
            if (cursor.moveToFirst()) {
                do {
                    // 遍历Cursor对象，取出数据并打印
                    val name = cursor.getString(cursor.getColumnIndex("name"))
                    val author = cursor.getString(cursor.getColumnIndex("author"))
                    val pages = cursor.getInt(cursor.getColumnIndex("pages"))
                    val price = cursor.getDouble(cursor.getColumnIndex("price"))
                    print(name+"-")
                    print(author+"-")
                    print(pages.toString()+"-")
                    println(price)
                } while (cursor.moveToNext())
            }
            cursor.close()
        }

    }
}